//
//  AppDelegate.m
//  QIRestorationDemo
//
//  Created by QLY on 2019/6/30.
//  Copyright © 2019 qishare. All rights reserved.
//

#import "AppDelegate.h"
#import "YSYTabBarController.h"
#import "YSYBaseViewController.h"
#import "YSYRestorationModel.h"

@interface AppDelegate ()
//
@property (nonatomic, strong) YSYTabBarController *rootViewController;
// 做一个临时变量，存储一下上一
@property (nonatomic, strong) YSYBaseViewController *lastViewController;
@end

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application willFinishLaunchingWithOptions:(NSDictionary<UIApplicationLaunchOptionsKey,id> *)launchOptions {
    self.window = [[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];
    self.window.backgroundColor = UIColor.whiteColor;
    return YES;
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    if (!self.window.rootViewController) {
        YSYTabBarController *tab = [[YSYTabBarController alloc]init];
        self.window.rootViewController= tab;
    }
    [self.window makeKeyAndVisible];
    return YES;
}


#pragma mark -- Restore, UI 的保存与恢复
- (BOOL)application:(UIApplication *)application shouldRestoreApplicationState:(NSCoder *)coder {
    return YES;
}

- (BOOL)application:(UIApplication *)application shouldSaveApplicationState:(NSCoder *)coder {
    return YES;
}

- (void)application:(UIApplication *)application didDecodeRestorableStateWithCoder:(NSCoder *)coder {
    self.rootViewController.lastViewController = self.lastViewController;
    // 避免造成内存泄漏
    self.lastViewController = nil;
}

- (UIViewController *)application:(UIApplication *)application viewControllerWithRestorationIdentifierPath:(NSArray<NSString *> *)identifierComponents coder:(NSCoder *)coder {
    NSString *lastIdentifier = identifierComponents.lastObject;
    UIViewController *vc = nil;
    // 根视图
    if (identifierComponents.count == 1) {
        vc = [[NSClassFromString(lastIdentifier) alloc] init];
        self.window.rootViewController = vc;
        if ([vc isKindOfClass:YSYTabBarController.class]) {
            self.rootViewController = (YSYTabBarController *)vc;
        }
        // 非根视图
    } else {
        YSYRestorationModel *model = [YSYBaseViewController getRestorationModelClassWithRestorationIdentifier:lastIdentifier];
        // 继承自 YSYBaseViewController
        if (model) {
            Class vcClass = NSClassFromString(model.classString);
            vc = [[vcClass alloc] init];
            NSLog(@">>>---%@---<<<", lastIdentifier);
            if (model.orderNumber > ((YSYBaseViewController *)self.lastViewController).restorationNumber) {
                self.lastViewController = (YSYBaseViewController *)vc;
                self.lastViewController.restorationNumber = model.orderNumber;
            }
        } else {
            vc = [[NSClassFromString(lastIdentifier) alloc] init];
        }
    }
    return vc;
}

@end
